package com.demo.feifan.mapperstruct;

import com.demo.feifan.entity.Test1;
import com.demo.feifan.entity.Test2;import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * map映射
 * @ Mapper (componentModel = "spring")的作用是创建一个Mapper接口的实现类，并注册到Spring容器中。
 */
@Mapper(componentModel = "spring")
public interface TestMapperConver {
    
    DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 映射测试数据
     * @param position
     * @return
     */
    @Mapping(source = "datetime", target = "datetime", qualifiedByName = "stringToLocalDateTime")
    Test1 toTest1(Test2 position);


    /**
     * 这个方法用于将字符串转换为LocalDateTime 对应上面toCommonTaxiGps那个@Mapping的qualifiedByName得属性
     * @param datetime
     * @return
     */
    @Named("stringToLocalDateTime")
    default LocalDateTime stringToLocalDateTime(String datetime) {
        if (datetime == null || datetime.trim().isEmpty()) {
            return null;
        }
        try {
            return LocalDateTime.parse(datetime, FORMATTER);
        } catch (DateTimeParseException e) {
            // 可以记录日志或根据需要处理解析异常
            return null;
        }
    }
}
